import { defineStore } from 'pinia';
import { ref } from 'vue';
import { login, set_branch, logout } from '@/api/auth';
import useTabStore from '@/stores/tabs';
import useRouterStore from '@/stores/router';
export default defineStore(
  'user',
  () => {
    const token = ref();
    const userInfo = ref({});
    const tabStore = useTabStore();
    const routerStore = useRouterStore();

    let tempToken, tempUserInfo;
    let pwdExps = [
      new RegExp('[A-Za-z]+'),
      new RegExp('[0-9]+'),
      new RegExp('[\x21-\x2e\x3a-\x40\x5b-\x60\x7b-\x7e]+'),
      new RegExp('[\x21-\x7e]{8,}')
    ];
    const userLogin = async (event) => {
      const { error, content } = await login(event);
      return new Promise((resolve, reject) => {
        if (error) {
          reject(error);
        } else {
          const { pretend, branch } = content;

          const result = { isLogin: true };
          tempToken = content.token;
          tempUserInfo = content.userInfo;
          if (branch) {
            if (branch?.children?.length) {
              result.isLogin = false;
              result.branch = branch?.children;
            } else {
              result.branch = branch.branchCode;
            }
          }
          if (pretend) {
            result.pretend = pretend;
            console.log(tempToken, 'tempToken');
            result.token = tempToken;
          }
          resolve(result);
        }
      });
    };

    const userEnter = async (event, code) => {
      const { error, content } = await set_branch(event, code, tempToken);
      return new Promise((resolve, reject) => {
        if (error) {
          reject(error);
        } else {
          token.value = tempToken;
          userInfo.value = tempUserInfo;
          resolve(content);
        }
      });
    };

    const userLogout = async (event) => {
      const { error, content } = await logout(event);
      return new Promise((resolve, reject) => {
        if (error) {
          reject(error);
        } else {
          clearUserStore();
          resolve(content);
        }
      });
    };

    const clearUserStore = () => {
      token.value = null;
      userInfo.value = null;
      routerStore.reset();
      tabStore.reset();
    };
    const pwdStrength = (pwd) => {
      if (!pwd) {
        return '';
      }
      var strength = 0;
      for (var i = 0; i < pwdExps.length; i++) {
        if (pwdExps[i].test(pwd)) {
          strength++;
        }
      }
      if (strength < 2) {
        return 'weak';
      } else if (strength < 4) {
        return 'medium';
      } else {
        return 'strong';
      }
    };
    return {
      token,
      userInfo,
      userLogin,
      userEnter,
      userLogout,
      clearUserStore,
      pwdStrength
    };
  },
  {
    persist: {
      enabled: true,
      strategies: [{ storage: localStorage, paths: ['token', 'userInfo'] }]
    }
  }
);
